#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys
import json
import cgi
import datetime
import db_conf
con = None
try:
    qform = cgi.FieldStorage()
    chromatogram_id = qform.getvalue('cid')
    config = db_conf.getConfig('metabvis.conf')
    con = psycopg2.connect(host=db_conf.getDBHost(config), database=db_conf.getDBName(config), port=db_conf.getDBPort(config), user=db_conf.getUser(config), password=db_conf.getPassword(config))
    cur = con.cursor()
    select_spectrums = 'select spectrum_id, RI, RT from spectrum where archived = 0 and chromatogram_id = ' + chromatogram_id
    cur.execute(select_spectrums)          
    rows = cur.fetchall()
    print "Content-type: text/html;charset=utf-8\r\n"
    url = "http://chart.apis.google.com/chart?cht=bvs&chs=200x125&chd=t:10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,10,50,60,80,40,&chco=4d89f9,c6d9fd&chbh=1,1&chds=0,160";
    j = []
    pa = {}
    pa['aaData'] = []
    for row in rows:
	pi = []
	for r in range(len(row)):
		#translate RT to min/sec
		if (r < 2):			
			pi.append(str(row[r]))
		else:
			rt_sec = float(row[r])/1000.0
			rt_min, rt_sec = divmod(rt_sec, 60)
			pi.append(str(rt_min) + " min " + str(rt_sec) + " sec")
		if (r+1 == len(row)):
			spectrum_id = str(row[0])
			select_intensity = 'select distinct(mz), intensity from spectral_peak where spectrum_id = %s order by mz asc' %(spectrum_id)
                	cur.execute(select_intensity)
                	intensity_rows = cur.fetchall()
			mz = []
                        intensity = []
			pos = 0 
			maxpos = 0
                	for i_row in intensity_rows:
				pos = pos + 1
                        	for ii in range(len(i_row)):
                                	if (ii == 0):
                                	        mz.append(i_row[ii])
                        	        if (ii == 1):
                	                        intensity.append(i_row[ii])
			imin = int(min(intensity))
			imax = int(max(intensity))
			"""if (len(intensity)>500):
				begin = maxpos - 200
				if (begin < 1):
					begin = 0
				end = maxpos + 200
				if (end > len(intensity)):
					end = len(intensity)
				range_intensity = intensity[begin:end]	 
				intensities = ",".join(str(i_val/1000).split(".")[0] for i_val in range_intensity)
			else:	
	                """
			intensities = ",".join(str(i_val).split(".")[0] for i_val in intensity)
			
			#full_intensities = ",".join(str(i_val/1000).split(".")[0] for i_val in intensity)
			mz_values = ",".join(str(i_val).split(".")[0] for i_val in mz)
			chds = "%s,%s" %(str(imin), str(imax))
			chart_url = "http://chart.apis.google.com/chart?cht=bvs&chs=200x125&chd=t:" + intensities + "&chbh=3,2&chds=" + chds 
			pi.append("<a href=javascript:plotMZIntensity('" + spectrum_id + "','" + intensities + "','" + mz_values + "')><img src='" + chart_url + "'></a>")
	pa['aaData'].append(pi)
    print json.dumps(pa)
except psycopg2.DatabaseError, e:
    print 'Error %s' % e    
    sys.exit(1)    
finally:
    if con:
        con.close()
